<template>
  <Card class="database-login" v-if="!hasLogin">
    <BasicForm @submit="handleSubmit" class="login-form" @register="register" v-bind="formConfig" />
  </Card>
  <Card class="database-login-ed">
    <Button type="primary" @click="handleAdd">
      <template #icon> <PlusOutlined /> </template>新增{{ configArr[currentLevel]?.tag }}
    </Button>
    <Button style="margin-left: 25px" @click="handleReturn" v-if="currentLevel != 0"> 返回 </Button>
    <div class="project-card"> </div>
    <div class="cardBody">
      <Card
        v-for="(project, index) in projectList"
        :key="index"
        style="width: calc((100vw - 258px) / 4); cursor: pointer"
        @click="handleView(project)"
      >
        <template #cover>
          <img :alt="project.label" src="@/assets/images/card/159 (1).png" />
        </template>
        <CardMeta :title="project.label" />
      </Card>
    </div>
    <BasicModal
      @ok="handleAddProject"
      @register="modalRegister"
      :title="'添加' + configArr[currentLevel]?.tag"
      :helpMessage="['提示1', '提示2']"
    >
      <BasicForm
        class="login-form"
        @register="register1"
        v-bind="formConfig1"
        v-if="currentLevel === 0 || currentLevel === 1"
      />
      <BasicForm v-else class="login-form" @register="register2" v-bind="formConfig1" />
    </BasicModal>
  </Card>
</template>
<script setup>
  import { nextTick, reactive, ref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { Card, CardMeta, Button } from 'ant-design-vue';
  import moment from 'moment';
  import { db } from '@/databaseInit/DexieRow.js';

  const [modalRegister, { openModal, setModalProps }] = useModal();
  const { ipcRenderer } = window.require('electron');
  let hasLogin = ref(false);
  let hasAdd = ref(false);

  let routers = reactive([]);

  let currentLevel = ref(0);

  let configArr = reactive([
    {
      tag: '项目',
      name: 'project',
    },
    {
      tag: '模块',
      name: 'module',
    },
    {
      tag: '接口',
      name: 'api',
    },
  ]);

  let projectList = reactive([]);
  let formConfig = reactive({
    labelAlign: 'right',
    labelWidth: 300,
    baseColProps: { span: 24 },
    autoSetPlaceHolder: true,
  });

  let formConfig1 = reactive({
    labelAlign: 'right',
    labelWidth: 300,
    baseColProps: { span: 24 },
    autoSetPlaceHolder: true,
    showResetButton: false,
    showSubmitButton: false,
  });

  const schemas = [
    {
      field: 'username',
      component: 'Input',
      label: '账号 : ',
      rules: [{ required: true }],
    },
    {
      field: 'password',
      component: 'InputPassword',
      label: '密码 : ',
      rules: [{ required: true }],
    },
    {
      field: 'connectString',
      component: 'Input',
      label: '数据库地址 : ',
      rules: [{ required: true }],
    },
  ];
  let oracleData = localStorage.getItem('oracleData');

  const [register, { setProps, updateSchema, getFieldsValue, setFieldsValue }] = useForm({
    labelWidth: 120,
    schemas,
    actionColOptions: {
      span: 24,
    },
  });

  const schemas1 = [
    {
      field: 'label',
      component: 'Input',
      label: '项目名称 : ',
      rules: [{ required: true }],
    },
  ];

  const [register1, { validate: validate1 }] = useForm({
    labelWidth: 120,
    schemas: schemas1,
    actionColOptions: {
      span: 24,
    },
  });

  const schemas2 = [
    {
      field: 'label',
      component: 'Input',
      label: '名称 : ',
      rules: [{ required: true }],
    },
    {
      field: 'path',
      component: 'Input',
      label: '路径 : ',
      rules: [{ required: true }],
    },
  ];

  const [register2, { validate: validate2 }] = useForm({
    labelWidth: 120,
    schemas: schemas2,
    actionColOptions: {
      span: 24,
    },
  });

  nextTick(() => {
    if (oracleData != null) {
      handleSubmit(JSON.parse(oracleData));
    }
  });

  let handleOk = () => {
    hasAdd.value = false;
  };

  let handleView = (row) => {
    routers.push({
      currentId: row.id,
      currentLevel: currentLevel.value,
      lastData: JSON.parse(JSON.stringify(projectList)),
    });
    currentLevel.value++;
    if (currentLevel.value === 1) {
      getModuleList(row.id);
    } else if (currentLevel.value === 2) {
      getApiList(row.id);
    } else if (currentLevel.value === 3) {
    }
  };
  let getProjectList = async () => {
    console.log(db.project, 'db.project');
    let newVar = (await db.project?.toArray()) || [];
    projectList.splice(0);
    projectList.push(...newVar);
  };

  let getModuleList = async (id) => {
    console.log(db?.module, 'db?.module');
    let newVar = await db.module.where({ id }).toArray();
    projectList.splice(0);
    projectList.push(...newVar);
  };
  let getApiList = async (id) => {
    let newVar = await db.api.where({ id }).toArray();
    projectList.splice(0);
    projectList.push(...newVar);
  };

  let handleReturn = () => {
    let pop = routers.pop();
    console.log(routers, 'routers');
    currentLevel.value--;
    projectList.splice(0);
    projectList.push(...pop.lastData);
  };

  getProjectList();

  let handleAddProject = async () => {
    if (currentLevel.value === 0 || currentLevel.value === 1) {
      validate1().then(async (res) => {
        let time = moment().format('YYYY-MM-DD HH:mm:ss');

        let data = {
          tenantId: null,
          revision: null,
          createdBy: null,
          createdTime: time,
          updatedBy: null,
          updatedTime: time,
          label: res.label,
        };

        if (currentLevel.value === 1) {
          data.projectId = routers[0].currentId;
          console.log(data, 'data');
          const id = await db.module.add(data);
          if (id) {
            openModal(false, {});
          }
        } else {
          const id = await db.project.add(data);

          if (id) {
            openModal(false, {});
          }
        }
      });
    } else if (currentLevel.value === 2) {
      validate2().then(async (res) => {
        let time = moment().format('YYYY-MM-DD HH:mm:ss');
        let data = {
          tenantId: null,
          revision: null,
          createdBy: null,
          createdTime: time,
          updatedBy: null,
          updatedTime: time,
          label: res.label,
          path: res.path,
          moduleId: routers[1].currentLevel,
        };
        const id = await db.api.add(data);
        openModal(false, {});
      });
    }
  };
  let handleAdd = () => {
    openModal(true, {});
  };

  //oracle 进行登录
  let handleSubmit = (fieldsValue) => {
    let tempData = getFieldsValue();
    if (tempData?.password !== undefined) {
      let fieldsValueString = JSON.stringify(fieldsValue);
      fieldsValue = getFieldsValue();
      localStorage.setItem('oracleData', fieldsValueString);
    } else if (fieldsValue?.password !== undefined) {
      console.log(fieldsValue, 'fieldsValue');
      setFieldsValue(fieldsValue);
    } else {
      return;
    }
    ipcRenderer.send('runDataBase', {
      data: fieldsValue,
      type: 'runDataBase',
    });
    // 监听来自主进程的响应事件
    ipcRenderer.on('runDataBase', (event, data) => {
      console.log(data, 'data');
      console.log(event, 'event');
      // 处理来自主进程的数据
      hasLogin.value = data;
    });
  };
</script>
<style scoped lang="less">
  .login-form {
    width: 450px;
    margin: 25% auto;
  }
  .database-login {
    height: 100%;
    background: url('/@/assets/images/database2.png');
  }
  .database-login-ed {
    height: 100%;
    background: url('/@/assets/images/project/652.png');
  }
  .project-card {
    margin-top: 25px;
  }
  .cardBody {
    display: flex;
    /deep/.ant-card {
      margin: 5px 10px;
    }
  }
</style>
